import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/bean/order_person_entity.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:jyofservice/util/TongJiEvent.dart';
import 'package:intl/intl.dart';

class RightEndDrawer extends StatefulWidget {

  String? type;
  //是否显示处理部门选项
  bool isOffstage;
  RightEndDrawer({this.type,this.isOffstage = true});

  @override
  _RightEndDrawerState createState() => _RightEndDrawerState();
}

class _RightEndDrawerState extends State<RightEndDrawer> {

  String? startTime;
  String? endTime;
  late SharedPreferences sharedPreferences;
  String? key;
  List<DropdownMenuItem> departList = [];
  late OrderPersonEntity departEntiy;
  String? departName;
  String? departId;

  List<DropdownMenuItem> personList = [];
  late OrderPersonEntity personEntity;
  String? personId;
  String? personName;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    startTime = DateFormat("yyyy-MM-dd").format(DateTime.now()).toString()+" "+"00:00:00";
    endTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()).toString();

    init().then((onValue) {
      if (onValue != null) {

        if(widget.type=="工单处理部门统计") {
          getDepartData();
        }

        if(widget.type=="工单处理维修员统计") {
          getPersonData();
        }
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child:GestureDetector(

          behavior: HitTestBehavior.translucent,
          onTap: (){

            FocusScope.of(context).requestFocus(FocusNode());
          },

          child:  Column(
            children: <Widget>[
              AppBar(
                centerTitle: true,
                title: Text(
                  '筛选',
                  style: TextStyle(
                      color: Colors.white, fontSize: ScreenUtil().setSp(45)),
                ),
                actions: <Widget>[
                  SizedBox(
                    width: 30,
                  )
                ],
              ),
              Container(
                width: ScreenUtil().scaleWidth,
                height: ScreenUtil().setHeight(2),
                color: Colors.grey,
              ),
              Expanded(
                flex: 8,
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.all(10),
                  child: SingleChildScrollView(
                      child: Column(
                        children: <Widget>[

                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                '开始时间:',
                                style: TextStyle(
                                    color: Colors.black87,
                                    fontSize: ScreenUtil().setSp(35)),
                              ),
                              SizedBox(
                                width: ScreenUtil().setWidth(10),
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: ScreenUtil().setHeight(80),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(5)),
                                    border: Border.all(color: Colors.grey),
                                  ),
                                  child: Row(
                                    children: <Widget>[
                                      TextButton(
                                        onPressed: () {
                                          DatePicker.showDateTimePicker(context,
                                              showTitleActions: true,
                                              onChanged: (date) {
                                                print('change $date');
                                              }, onConfirm: (date) {
                                                print('confirm $date');
                                                if (mounted) {
                                                  setState(() {
                                                    startTime =
                                                        date.toString()
                                                            .substring(0, 19);
                                                  });
                                                }
                                              },
                                              currentTime: DateTime.now(),
                                              locale: LocaleType.zh);
                                        },
                                        child: Text(
                                          startTime ?? '请 选 择 开 始 时 间',
                                        ),
                                      ),
                                      Offstage(
                                        offstage: startTime==null?false:true,
                                        child: Icon(Icons.arrow_drop_down),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: ScreenUtil().setHeight(20),
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                '结束时间:',
                                style: TextStyle(
                                    color: Colors.black87,
                                    fontSize: ScreenUtil().setSp(35)),
                              ),
                              SizedBox(
                                width: ScreenUtil().setWidth(10),
                              ),
                              Expanded(
                                flex: 1,
                                child: Container(
                                  height: ScreenUtil().setHeight(80),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(5)),
                                    border: Border.all(color: Colors.grey),
                                  ),
                                  child: Row(
                                    children: <Widget>[
                                      TextButton(
                                        onPressed: () {
                                          DatePicker.showDateTimePicker(context,
                                              showTitleActions: true,
                                              onChanged: (date) {
                                                print('change $date');
                                              }, onConfirm: (date) {
                                                print('confirm $date');
                                                if (mounted) {
                                                  setState(() {
                                                    endTime =
                                                        date.toString()
                                                            .substring(0, 19);
                                                  });
                                                }
                                              },
                                              currentTime: DateTime.now(),
                                              locale: LocaleType.zh);
                                        },
                                        child: Text(
                                          endTime ?? '请 选 择 结 束 时 间',
                                        ),
                                      ),
                                      Offstage(
                                        offstage: endTime==null?false:true,
                                        child:  Icon(Icons.arrow_drop_down),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: ScreenUtil().setHeight(20),
                          ),
                          Offstage(
                            offstage: widget.type=='工单处理部门统计'?false:true,
                            child: getDepartRow(),
                          ),
                          Offstage(
                            offstage: widget.type=='工单处理维修员统计'?false:true,
                            child: getPersonRow(),
                          )

                        ],
                      )),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Container(

                    color: Colors.white,
                    margin:EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                    alignment: Alignment.bottomCenter,

                    child: Row(

                      children: <Widget>[
//                        Expanded(
//
//                          child: Container(
//                              decoration: BoxDecoration(
//                                  border: Border.all(width: 1.0,color: Color(0xff4c8eff)), color: Colors.white
//                              ),
//                              height: 60.0,
//                              child:FlatButton(
//                                child: Text("重置",style: TextStyle(color:const Color(0xFF3090ff),fontSize: ScreenUtil().setSp(28) ),),
//                                onPressed:(){
//
//                                  startTime = null;
//                                  endTime = null;
//
//                                  if (mounted) {
//                    setState(() {
//
//                                  });}
//                                },
//                              )
//                          ),
//                        ),
                        Expanded(

                          child: Container(
                              decoration: BoxDecoration(

                                border: Border.all(width: 1.0,color: Color(0xff4c8eff)),
                                color: Color(0xff4c8eff),

                              ),
                              height: 60.0,
                              child:TextButton(

                                child: Text("查询",style: TextStyle(color: Colors.white,fontSize: ScreenUtil().setSp(35) ),),
                                onPressed: () {

                                  _chaxun();

                                },
                              )
                          ),
                        ),

                      ],
                    ),
                  )

              )
            ],
          ),
        )
    );
  }

  void _chaxun() {

    if (startTime == null) {

      Fluttertoast.showToast(

        msg: "请选择开始时间",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,

      );

      return;

    }

    if (endTime == null) {
      Fluttertoast.showToast(

        msg: "请选择结束时间",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,

      );

      return;
    }

    Constants.eventBus.fire(TongJiEvent(type: widget.type,startTime: startTime,endTime: endTime,departmentId: departId,userId: personId));

    NavigatorUtil.goBack(context);
  }

  Future init() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  //处理人员
  Widget getPersonRow() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理人员：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: personName,
                items: personList,
                hint: Text('请选择处理人员'),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      personName = T;

                      for (int i = 0; i < personEntity.data!.length; i++) {
                        if (personEntity.data![i].name == personName) {
                          personId = personEntity.data![i].iD.toString();
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //处理部门
  Widget getDepartRow() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理部门：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: departName,
                items: departList,
                hint: Text('请选择处理部门'),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      departName = T;
                      for (int i = 0; i < departEntiy.data!.length; i++) {
                        if (departEntiy.data![i].name == departName) {
                          departId = departEntiy.data![i].iD.toString();
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //获取处理人员
  Future getPersonData() async {
    personList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "ChuLiRenYuan",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    personEntity = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (personEntity.code == "200") {
      if (mounted) {
        setState(() {
          personList = new List<DropdownMenuItem>.generate(
              personEntity.data!.length,
                  (i) => new DropdownMenuItem(
                  child: new Text(
                    personEntity.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: personEntity.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //获取处理部门
  Future getDepartData() async {
    departList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Sys_department_basic",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Department_name",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    departEntiy = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (departEntiy.code == "200") {
      if (mounted) {
        setState(() {
          departList = new List<DropdownMenuItem>.generate(
              departEntiy.data!.length,
                  (i) => new DropdownMenuItem(
                  child: new Text(
                    departEntiy.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: departEntiy.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

}
